#include "Dictionary.h"
#include "nlohmann/json.hpp"
#include <iostream>
#include <fstream>
#include <sstream>

using std::cerr;
using std::cout;
using std::ifstream;

Dictionary *Dictionary::_diction = nullptr;

Dictionary::reaslse Dictionary::_quit;

Dictionary::reaslse::reaslse()
{
}

Dictionary::reaslse::~reaslse()
{
    if (_diction)
    {
        delete _diction;
        _diction = nullptr;
    }
}
Dictionary::Dictionary()
{
}
Dictionary *Dictionary::getInstance()
{
    if (_diction == nullptr)
    {
        _diction = new Dictionary();
    }
    return _diction;
}
void Dictionary::init()
{
    ifstream DictIfs("/home/sakura/all_file/search_engine/data/dict.dat");
    if (!DictIfs)
    {
        cerr << "dict wrong\n";
    }
    std::ostringstream oss;
    oss << DictIfs.rdbuf();
    string DictDat = oss.str();
    nlohmann::json json = nlohmann::json::parse(DictDat);
    for (const auto &i : json)
    {
        _dict.emplace_back(i[0], i[1]);
    }
    ifstream Indexifs("/home/sakura/all_file/search_engine/data/dictIndex.dat");
    if (!Indexifs)
    {
        cerr << "index wrong\n";
    }
    std::ostringstream Indexoss;
    Indexoss << Indexifs.rdbuf();
    string IndexDat = Indexoss.str();
    nlohmann::json Indexjson = nlohmann::json::parse(IndexDat);
    for (auto &[key, value] : Indexjson.items())
    {
        _index.emplace(key, value);
    }
}

vector<pair<string, int>> &Dictionary::getVector()
{
    return _dict;
}
map<string, set<int>> &Dictionary::queryIndex()
{
    return _index;
}
int Dictionary::distance(string candidate)
{
    return 0;
}
